<?php

namespace app\api\biz;

use app\common\biz\Biz;
use app\common\enum\Code;
use app\common\model\biz\SysRoleMenu;
use app\common\Result;
use Exception;
use think\db\exception\DbException;

class RoleMenuBiz extends Biz
{

    public static function list(int $roleId): RoleMenuBiz
    {
        if (empty($roleId)) {
            return self::errorByCode(Code::ParamsInvalid);
        }
        $lists = SysRoleMenu::where('role_id', $roleId)->select();
        return self::success($lists);
    }

    public static function add(int $roleId, array $menuIds): RoleMenuBiz
    {
        if (empty($roleId)) {
            return self::errorByCode(Code::ParamsInvalid);
        }

        try {
            SysRoleMenu::where('role_id', $roleId)->delete();
            foreach ($menuIds as $menuId) {
                SysRoleMenu::create(['role_id' => $roleId, 'menu_id' => $menuId]);
            }
            return self::success();
        } catch (DbException $e) {
            Result::dbException($e->getData());
        } catch (Exception $e) {
            Result::httpException($e->getMessage());
        }
    }
}